//
//  BBSAddCaseController.m
//  QuickCure
//
//  Created by 石玄机 on 16/9/13.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "BBSAddCaseController.h"
#import "BBSDiseaseTypeController.h"
#import "BBSDiseaseSubdivideController.h"
#import "BBSAddCaseModel.h"
#import "BBSAddPhotoCell.h"

#define kPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"case.plist"]

static NSString *reuserId = @"cell";

@interface BBSAddCaseController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextViewDelegate>

//症状描述
@property (weak, nonatomic) UILabel *caseDiscLabel;

//症状描述testView
@property (weak, nonatomic) UITextView *textView;

//整个tableView
@property (weak, nonatomic) UITableView *tableView;

//症状描述和病例照片的cell
@property (weak, nonatomic) UITableViewCell *bigCell;

//疾病类型和疾病细分的cell
@property (weak, nonatomic) UITableViewCell *smallCell;


//添加本地照片的button
@property (weak, nonatomic) UIButton *addPhotoBtn;

//传回来的疾病类型
@property (copy, nonatomic) NSString *typeString;

//传回来的疾病细分
@property (copy, nonatomic) NSString *subdivide;

//病例模型
@property (strong, nonatomic) BBSAddCaseModel *model;

//病例模型数组
@property (strong, nonatomic) NSMutableArray *caseModelArray;

//选择的本地图片
@property (strong, nonatomic) UIImage *selectedImage;



@end

@implementation BBSAddCaseController

/** 实例化懒加载模型数组, 从存储的路径读取本地数据 */
- (NSMutableArray *)caseModelArray{
    
    if (_caseModelArray == nil) {
        
        NSArray *arr = [NSArray arrayWithContentsOfFile:kPath];
        
        _caseModelArray = [[NSMutableArray alloc]initWithArray:arr];
    }
    return  _caseModelArray;
    
}


/** 实例化懒加载model */
-(BBSAddCaseModel *)model{
    
    if (_model == nil) {
        
        _model = [[BBSAddCaseModel alloc]init];
    }
    
    return _model;
}



-(void)setTypeString:(NSString *)typeString{
    
    _typeString = typeString;
    
    self.model.diseaseType = typeString;
}

-(void)setSubdivide:(NSString *)subdivide{
    
    _subdivide = subdivide;
    
    self.model.subdivideType = subdivide;
    
}



- (UITableView *)tableView{
    
    if (!_tableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        
        self.tableView = tableView;
        
        [self.tableView registerClass:[BBSAddPhotoCell class] forCellReuseIdentifier:reuserId];
    }
    return  _tableView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI{
    
    [self setupNavigationBarItem];
    [self setupTableView];
}

//设置BarButtonItem上的按钮等
- (void)setupNavigationBarItem{
    
    self.title = @"增加病例";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitCase)];
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor blackColor]];
    
    
}


#pragma mark
#pragma mark - 点击提交按钮后把数据返回给上一个控制器
- (void)submitCase{
    //先判断是否有疾病细分, 没有的话提示用户输入
    if (self.subdivide.length == 0) {
        [self alertWithMessage:@"请选择疾病细分" actionTitle:@"确定"];
        return;
    }
    
    self.model.textViewText = self.textView.text;
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    formatter.dateFormat= @"yyyy-MM-dd hh:mm:ss";
    
    NSString *dateString = [formatter stringFromDate:date];
    
    self.model.addTime = dateString;
    
    NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:self.model];
    
    //先把二进制数据插入到数组的第一个
    [self.caseModelArray insertObject:modelData atIndex:0];
    
    //存到Document
    
    if ([self.caseModelArray writeToFile:kPath atomically:YES])
    {
//        NSLog(@"%@", kPath);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self alertWithMessage:@"数据提交失败" actionTitle:@"确定"];
    }
    
    //FIXME: 这里存进Document后就不需要Block传值过去了
    //    if (self.modelBlock) {
    //
    //        self.modelBlock(self.model);
    //    }
    
    
    
}


#pragma mark
#pragma mark - 设置tableView页面

-(void)setupTableView{
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}


#pragma mark - 数据源方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        UITableViewCell *smallCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        smallCell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.smallCell = smallCell;
        
        if (indexPath.row == 0) {
            smallCell.textLabel.text = @"疾病类型";
            [smallCell setTintColor:[UIColor blackColor]];
            smallCell.textLabel.font = FONT(18);
            smallCell.detailTextLabel.font = FONT(16);
            
            if (!self.typeString) {
                smallCell.detailTextLabel.text = @"请选择";
            }else{
                smallCell.detailTextLabel.text = self.typeString;
            }
            
            [smallCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            
            
        }else if(indexPath.row == 1){
            smallCell.textLabel.text = @"疾病细分";
            [smallCell setTintColor:[UIColor blackColor]];
            smallCell.textLabel.font = FONT(18);
            smallCell.detailTextLabel.font = FONT(16);
            smallCell.detailTextLabel.text = @"请选择";
            [smallCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            
            if (self.subdivide) {
                
                smallCell.detailTextLabel.text = self.subdivide;
            }
            
            
        }
        
        return smallCell;
        
    }else {
        
        UITableViewCell *bigCell = [[UITableViewCell alloc] init];
        bigCell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.bigCell = bigCell;
        
        if (indexPath.row == 0) {
            
            UILabel *caseDiscLabel = [[UILabel alloc]init];
            caseDiscLabel.text = @"病症描述:";
            caseDiscLabel.font = FONT(18);
            [bigCell.contentView addSubview:caseDiscLabel];
            self.caseDiscLabel = caseDiscLabel;
            
            [caseDiscLabel makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(bigCell.contentView).offset(10);
                make.left.equalTo(bigCell.contentView).offset(15);
                
            }];
            
            UITextView *textView = [[UITextView alloc] init];
            self.textView = textView;
            textView.delegate = self;
            textView.backgroundColor = [UIColor colorWithRed:0.940 green:1.000 blue:0.952 alpha:1.000];
            //FIXME: textView字体等
            [bigCell.contentView addSubview:textView];
            
            [textView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.caseDiscLabel.bottom).offset(10);
                make.left.right.bottom.equalTo(bigCell.contentView).insets(UIEdgeInsetsMake(0, 10, 10, 10));
            }];
            
            UIView * lineView = [[UIView alloc] init];
            lineView.backgroundColor = [UIColor lightGrayColor];
            [bigCell addSubview: lineView];
            [lineView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(bigCell.bottom).offset(-1);
                make.height.equalTo(1);
                make.left.right.equalTo(bigCell).insets(UIEdgeInsetsMake(0, 10, 0, 10));
            }];
            
            
        }else if (indexPath.row == 1){
            
            WEAKSELF;
            BBSAddPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserId];
            
            [cell setAddPhotoBlock:^(UIButton *button) {
                
                weakSelf.addPhotoBtn = button;
                
                [weakSelf addPhotoBtnClick];
                
            }];
            
            
            return cell;
            
            
        }
        return bigCell;
    }
}


#pragma mark
#pragma mark - 添加相册图片
- (void)addPhotoBtnClick{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    
    [pickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    pickerController.delegate = self;
    
    [self presentViewController:pickerController animated:YES completion:nil];
}


#pragma mark
#pragma mark - UIImagePickerController 代理方法 --> 获取相册里的图片

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info{
    //获取选中的image
    UIImage *selectedImage = info[@"UIImagePickerControllerOriginalImage"];
    
    NSData *data = UIImagePNGRepresentation(selectedImage);
    
    
    
    self.model.imageData = data;
    
    
    //添加到uibutton
    [self.addPhotoBtn setBackgroundImage:selectedImage forState:UIControlStateNormal];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark
#pragma mark - TableViewCellDelegate 代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (!self.typeString && indexPath.section == 0 && indexPath.row == 1) {
        
        [self alertWithMessage:@"请先选择疾病类型" actionTitle:@"确定"];
        
        return;
        
    }
    
    
    
    if (indexPath.section == 0) {
        
        if(indexPath.row == 0) {
            
            
            BBSDiseaseTypeController *diseaseTypeController = [[BBSDiseaseTypeController alloc] init];
            
            
            WEAKSELF;
            //给typeBlo;ck赋值(把值传回给自己)
            diseaseTypeController.typeBlock = ^(NSString *str){
                
                weakSelf.typeString = str;
                [weakSelf.tableView reloadData];
            };
            [self.navigationController pushViewController:diseaseTypeController animated:YES];
        }
        else{
            
            BBSDiseaseSubdivideController *diseaseSubdivideController = [[BBSDiseaseSubdivideController alloc] init];
            //在这里把拿到的疾病类型的值赋给了疾病细分的typeString类型, 这样typeController一旦拿到了值, 就会顺传给即将跳转的疾病细分页面.
            diseaseSubdivideController.typeString = self.typeString;
            
            WEAKSELF;
            //给subdivideBlock赋值(把值传回给自己)
            diseaseSubdivideController.subdivideBlock = ^(NSString *string){
                
                weakSelf.subdivide = string;
                
                [weakSelf.tableView reloadData];
                
            };
            
            [self.navigationController pushViewController:diseaseSubdivideController animated:YES];
        }
    }
}


#pragma mark
#pragma mark - 把heightForHeaderInSection的值设置为
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 50;
    }else{
        return 180;
    }
}



#pragma mark
#pragma mark - 自定义一个UIAlert 弹窗方法


- (void)alertWithMessage:(NSString *)message actionTitle:(NSString *)actionTitle{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:sure];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    return;
}



- (void)dealloc{
    
     NSLog(@"%s, %i", __func__, __LINE__);
}


@end









































